<!--新的页面-->

<template>
  <div>
    <table-ext :columns="columns" :searchForm="searchForm" :config="config" ref="tableExt">
      <template slot="table-action">
        <el-button type="primary" icon="el-icon-plus" @click="addUserDialog">新增</el-button>
      </template>
    </table-ext>
    <el-dialog :title="dialogUpdate?'修改':'新增' + config.title" :rules="rules" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <el-input v-if='isShow' v-model="form.id"></el-input>
        <el-form-item label="全称" :label-width="formLabelWidth">
          <el-input v-model="form.name" auto-complete="off"></el-input>
        </el-form-item>
          
        <el-form-item label="联系电话" :label-width="formLabelWidth">
          <el-input v-model="form.mobilePhone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="工号" :label-width="formLabelWidth">
          <el-input v-model="form.empNo" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="公司" :label-width="formLabelWidth">
          <el-select v-model="form.companyId" placeholder="请选择">
            <el-option v-for="item in selectCompanyData" :key="item.companyName" :label="item.companyName" :value="item.id"></el-option>
          </el-select>

        </el-form-item>
        <!-- <el-form-item label="供应商名称" :label-width="formLabelWidth">
          <el-select v-model="form.vendorId" placeholder="请选择">
            <el-option v-for="item in selectVendorData" :key="item.label" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="供应商" :label-width="formLabelWidth">
                <select-table v-model="vendorData" @on-selection-data="getRowData"></select-table>
              </el-form-item>
        <el-form-item label="岗位选择" :label-width="formLabelWidth">
          <el-select v-model="form.stationId" placeholder="请选择">
            <el-option v-for="item in selectStationData" :key="item.stationName" :label="item.stationName" :value="item.id"></el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="集采权限" :label-width="formLabelWidth">
          <el-radio-group v-model="form.cpFlag">
            <el-radio label="0">无</el-radio>
            <el-radio label="1">有</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetNewForm(); dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdate('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="锁定用户" :visible.sync="dialoglockVisible">
      <el-form :model="lockform">
        <el-input v-if='isShow' v-model="lockform.id"></el-input>
        <el-form-item label="锁定原因" :label-width="formLabelWidth">
          <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="lockform.lockReason">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialoglockVisible = false">取 消</el-button>
        <el-button type="primary" @click="lockUser(lockform)">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="dialogAllowRoleVisible" :close-on-click-modal="false" :show-close="false">
      <el-form :model="roleform">
        <el-input v-if='isShow' v-model="roleform.id"></el-input>
        <template>

          <div style="text-align: center">
            <!-- <el-transfer style="text-align: left; display: inline-block" v-model="roleform.roleIdss" filterable :render-content="renderFunc"
              :titles="['可选角色', '已选角色']" :button-texts="['到左边', '到右边']" :format="{
        noChecked: '${total}',
        hasChecked: '${checked}/${total}'
      }" :data="roledata">
            </el-transfer> -->
            <vendors-transfer ref="trans" 
                width="100%" :checkName="['code','description']" 
                 :title="{left:'可选角色',right:'已选角色'}"
                :searchForm="searchRoleForm" :selectData="roleform.roleIdss" :isQsparams = false
                :url="lib.config.host.system + '/system/rolemgt/roles/query'">
                </vendors-transfer>
          </div>

        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resrRoleForm">取 消</el-button>
        <el-button type="primary" @click="allowRole(roleform)">确 定</el-button>
       
      </div>
    </el-dialog>
     <!-- <el-button type="primary" @click="testDate()">测试数据</el-button> -->
  </div>
</template>

<script>

  import TableExt from '@/components/common/table-ext/table-ext.vue';
  import SelectTable from '@/components/common/select-ext/select-table';
    import vendorsTransfer from '@/components/common/select-ext/vendorsTransfer.vue';
   import qs from 'qs';
  export default {
    // 引入自定义表格组件
    components: {
      'table-ext': TableExt,
       SelectTable,
      vendorsTransfer
    },
    data() {
      return {
        value1 :'',
        isShow: false,
        dialogFormVisible: false,
        dialoglockVisible: false,
        dialogAllowRoleVisible: false,
        dialogUpdate: false,
        dialogTitle: '',
        roledata: [],
        vendorData:'',
        selectVendorData: [
          {
            label: '上海阳安光电有限公司',
            value: '1484'
          },
          {
            label: '上海蓝英仪器仪表有限公司',
            value: '1494'
          }
        ],
        searchRoleForm :[
          {key:'description',type:'text',placeholder:'请输入名称',value:''}],
        selectCompanyData: [],
        selectStationData:[],
        formLabelWidth: '120px',
        form: {

        },
        updateForm: {

        },
        lockform: {

        },
        roleform　: {
          roleIds: '',
          roleIdss: []
        },
        testForm : {
          countryCode :''
        },
        //校验
        rules: {
          name: [{
            required: true,
            message: '请填写姓名',
            trigger: 'blur'
          }],
          mobilePhone: [{
            required: true,
            message: '请填写联系电话',
            trigger: 'blur'
          }, ],
          vendorId: [{
            required: true,
            message: '请填写供应商',
            trigger: 'blur'
          }]
        },
        checkIds: [],
        rolesIdDate: [],
        show2: false,
        config: { // 页面共通配置
          title: '用户列表', //页面标题
          isPage: true, //是否分页
          isNo: false, //是否显示序号
          selection: true, //是否显示复选框
          crudMapping: { // CRUD方法
            query: {
              url: this.lib.config.host.system + '/system/usermgt/users/query',
            },
            delete: {
              url: this.lib.config.host.system + '/system/usermgt/users/deleteMuilt',
            }
          }
        },
        // 查询表单配置
        searchForm: [{
          //显示标签
          label: '邮箱',
          //数据字段
          key: 'email',
          //标签类型
          type: 'input'
        }, {
          label: '姓名',
          key: 'name',
          type: 'input'
        }, {
          label: '所属公司',
          key: 'companyName',
          type: 'input'
        },
        {
          label: '供应商名称',
          key: 'vendorName',
          type: 'input'
        }, {
          label: '用户状态',
          key: 'status',
          // 下拉多选
          type: 'multipleSelect',
          dict: [{
            key: '0',
            value: '启用'
          }, {
            key: '1',
            value: '禁用'
          }]
        }],
        // 表格列定义
        columns: [{
          width: '500px',
            label: '操作', // 表格header
            render: (createElement, params) => { // 动态渲染，click事件示例
              let _this = this;
              return createElement('div', {
                width: "500px"
              }, [createElement('el-button', {
                  props: {
                    type: 'text',
                  },
                  on: {
                    click() {
                      _this.form = Object.assign({}, _this.form, params.row);
                      _this.dialogUpdate = true;
                      _this.dialogFormVisible = true
                    }
                  }
                }, '编辑'),
                createElement('el-button', {
                  props: {
                    type: 'text',
                  },
                  on: {
                    click() {
                      _this.deleteUser(params.row.id);
                    }
                  }
                }, '删除'),
                createElement('el-button', {
                  props: {
                    type: 'text',
                  },
                  on: {
                    click() {
                      _this.resetPwd(params.row.id);
                    }
                  }
                }, '重置密码'),
                createElement('el-button', {
                  props: {
                    type: 'text',
                  },
                  on: {
                    click() {
                      if (params.row.status == 1) {
                        _this.lock(params.row.id, 0);
                      }

                    }
                  }
                }, '禁用'),
                createElement('el-button', {
                  props: {
                    type: 'text',
                  },
                  on: {
                    click() {
                      if (params.row.status == 0) {
                        _this.lock(params.row.id, 1);
                      }
                    }
                  }
                }, '启用'),
                createElement('el-button', {
                  props: {
                    type: 'text',
                  },
                  on: {
                    click() {
                      _this.lockUserDialog(params.row.id);
                    }
                  }
                }, '锁定'),
                createElement('el-button', {
                  props: {
                    type: 'text',
                  },
                  on: {
                    click() {
                      _this.allowRoleUser(params.row.id);
                    }
                  }
                }, '分配角色'),
                createElement('el-button', {
                  props: {
                    type: 'text',
                  },
                  on: {
                    click() {
                      _this.$router.push({
                        path: '/Index/System/UserAllowDataAuth',
                        query: {
                          userId: params.row.id
                        }
                      })
                    }
                  }
                }, '分配数据权限')
              ]);
            }
          }, {
            label: '邮箱',
            key: 'email',
            width : "150px",
            align :'center'
          },
          {
            label: '姓名',
            key: 'name',
             width : "150px",
             align :'center'
          },
          {
            label: '公司',
            key: 'company.companyName',
             width : "150px",
             align :'center'
          },
          {
            label: '供应商名称',
            key: 'organization.vendorName',
             width : "150px",
             align :'center'
          },
          {
            label: '联系电话',
            key: 'mobilePhone',
            width : "150px",
            align :'center'
          },
          {
            label: '创建日期',
            key: 'createTime',
             width : "150px",
             align :'center'
          },
          {
            label: '用户状态',
            align :'center',
            key: 'status',
            render:(createElement, params)=>{ //动态渲染, 字典表示例
           if(0 == params.row.status || -2 == params.row.status || 2 == params.row.status ) {
              return createElement('div', '启用');
            }
            else if (1 == params.row.status || -1 == params.row.status) {
              return createElement('div', '禁用');
            }      
          }
          }
        ]
      }
    },
    mounted() {
      this.queryCompanyData();
      this.queryStationData();
      // this.queryVendorData();
    },
    methods: {
       // 双击供应商触发
      getRowData(data){
        this.form.vendorId = data.id;
   
      },
      //查询所有公司信息
      queryCompanyData(){
          this.axios.post(this.lib.config.host.masterData + '/system/cmpMgt/company/getAll', {}).then((res)=>{
              this.selectCompanyData = res.data;
          })
      },
      queryStationData(){
          this.axios.post(this.lib.config.host.system + '/system/usermgt/users/getAllStation', {}).then((res)=>{
              this.selectStationData = res.data;
          })
      },
      //  queryVendorData(){
      //     this.axios.post(this.lib.config.host.system + '/system/orgmgt/organization/query', {}).then((res)=>{
      //       debugger;
      //         this.selectVendorData = res.data.row;
      //     })
      // },
      // changeValue(value) {
      //   alert(value);
      //   let obj = {};
      //   obj = this.selectVendorData.find((item) => {
      //     return item.value === value;
      //   });
      //   this.form.vendorName = obj.label
      // },
      addUserDialog() {
        //弹出新增窗口
        this.dialogUpdate = false;
        this.dialogTitle = "用户新增",
          this.dialogFormVisible = true;

        this.resetNewForm();
      },
      resetNewForm() {
        this.form = {}
      },
      saveOrUpdate(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.axios.post(this.lib.config.host.system + '/system/usermgt/users/saveOrUpdate', this.form).then((
              res) => {
              this.$refs['tableExt'].refreshTable();
              this.dialogFormVisible = false;
              this.form.vendorName = ''
            }).catch((e) => {
              this.$message({
                type: 'info',
                message: '更新失败！'
              });
            });
          } else {
            return false;
          }
        })
        // this.dialogFormVisible = false;
        // this.securityPost(this.lib.config.host.system+"/system/usermgt/users/saveOrUpdate", form)
        //   .then((response) => {
        //     this.submitForm()
        //   })
        //   .catch((error) => {
        //     console.log(error);
        //   });

      },
      batchDelete() {
     
            //删除操作
            // let checkRows = this.$refs['tableExt'].multipleSelection;
            // // let checkRows = this.multipleSelection;
            // checkRows.map(item => {
            //   console.log(item.id);
            //   this.checkIds.push(item.id);
            // });
            // this.axios.post(this.lib.config.host.system + "/system/usermgt/users/deleteMuilt", this.checkIds)
            //   .then((response) => {
            //     this.$refs['tableExt'].refreshTable();
            //     this.$message({
            //       type: 'success',
            //       message: '删除成功!'
            //     });

            //   })
            //   .catch((error) => {
            //     this.$message({
            //       type: 'info',
            //       message: '删除成功!'
            //     });
            //   });
            
     this.$confirm('是否确认删除用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
               //删除操作
            let checkRows = this.$refs['tableExt'].multipleSelection;
            // let checkRows = this.multipleSelection;
            checkRows.map(item => {
              console.log(item.id);
              this.checkIds.push(item.id);
            });
            this.axios.post(this.lib.config.host.system + "/system/usermgt/users/deleteMuilt", this.checkIds)
              done();
            } else {
              done();
            }
          }
        }).then((response) => {
          this.checkIds = []
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch((error) => {
          this.checkIds = []
          this.$message({
            type: 'info',
            message: '操作失败'
          });
        });
      },
      allowDataAuth(id) {
        //分配数据权限
        //this.$router.push('/Index/System/UserAllowDataAuth?userId='+ id)
        this.$router.push({
          path: '/Index/System/UserAllowDataAuth',
          query: {
            userId: id
          }
        })
      },
      resetPwd(id) {
        //重置密码
        this.$confirm('是否确认重置密码?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              this.axios.post(this.lib.config.host.system + "/system/usermgt/users/resetPwd/" + id)
              done();
            } else {
              done();
            }
          }
        }).then((response) => {
          this.$message({
            type: 'success',
            message: '重置成功!'
          });
        }).catch((error) => {
          this.$message({
            type: 'info',
            message: '已取消重置密码'
          });
        });
      },
      lock(id, status) {
        //启用,禁用
        this.axios.post(this.lib.config.host.system + "/system/usermgt/users/lock/" + id + "/" + status)
          .then((response) => {
            this.$refs['tableExt'].refreshTable();
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
          }).catch((error) => {
            this.$message({
              type: 'info',
              message: '取消操作'
            });
          });
      },
      lockUserDialog(id) {
        this.lockform.id = id;
        this.dialoglockVisible = true
      },
      lockUser() {
        //锁定用户
        this.axios.post(this.lib.config.host.system + "/system/usermgt/users/lockUser/", this.lockform)
          .then((response) => {
            debugger;
            this.$refs['tableExt'].refreshTable();
            this.dialoglockVisible = false;
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
          }).catch((error) => {
            debugger;
            this.$message({
              type: 'info',
              message: '取消操作'
            });
          });
      },
      deleteUser(id) {
        //删除用户
        // this.axios.post(this.lib.config.host.system + "/system/usermgt/users/delete/" + id)
        //   .then((response) => {
        //     this.$refs['tableExt'].refreshTable();
        //     this.$message({
        //       type: 'success',
        //       message: '删除成功!'
        //     });
        //   }).catch((error) => {
        //     this.$message({
        //       type: 'info',
        //       message: '取消成功'
        //     });
        //   });

        this.$confirm('是否删除用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              this.axios.post(this.lib.config.host.system + "/system/usermgt/users/delete/" + id)
              done();
            } else {
              done();
            }
          }
        }).then((response) => {
          this.$refs['tableExt'].refreshTable();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch((error) => {
          this.$message({
            type: 'info',
            message: '操作失败！'
          });
        });
      },
      formateStatus: function (row, column, cellValue, index) {
        debugger;
        if (cellValue == 1) {
          return "启用"
        } else {
          return "禁用"
        }
      },
      restForm: function () {
        this.formInline = {}
      },
      allowRoleUser(id) {
        debugger;
        //左右选初始化弹框加载
        this.dialogAllowRoleVisible = true;
        this.roleform.id = id;　

        // this.axios.post(this.lib.config.host.system + "/system/rolemgt/roles/query", {
        //     pageNo: 1,
        //     pageSize: 100
        //   }).then((response) => {
        //     for (var i = 0; i < response.data.rows.length; i++) {
        //       this.roledata.push({
        //         key: response.data.rows[i].id,
        //         label: '【' + response.data.rows[i].code + '】' + response.data.rows[i].description


        //       });
        //     }

        //   })
        //   .catch(function (error) {
        //     console.log(error);
        //   });

        // this.axios.post(this.lib.config.host.system + "/system/usermgt/users/queryUserRole/" + id).then((response) => {
        //     debugger;
        //     if (response.data.length > 0) {
        //       for (var i = 0; i < response.data.length; i++) {
        //         this.roleform.roleIdss.push(response.data[i].id);
        //       }
        //       this.rolesIdDate.map(item => {
        //         console.log(item);
        //       });
        //     }
        //   })
        //   .catch(function (error) {
        //     console.log(error);
        //   });

        //穿梭框右边数据获取
        this.axios.post(this.lib.config.host.system + "/system/usermgt/users/queryUserRole/"+id).then((res) => {
          this.roleform.roleIdss=res.data;
           //采购组织     
          this.$nextTick(()=>{
            this.$refs.trans.resetCheck();
          })
        })
        .catch(function (error) {
            console.log(error);
        });
      },
      allowRole() {
        //角色保存
        if (this.roleform.roleIdss.length > 0) {
          for (var i = 0; i < this.roleform.roleIdss.length; i++) {
            this.roleform.roleIds += this.roleform.roleIdss[i].id + ","
          }
          this.roleform.roleIds = this.roleform.roleIds.substr(0, this.roleform.roleIds.length - 1);

          console.log(this.roleform.roleIds);
        }
        this.axios.post(this.lib.config.host.system + "/system/usermgt/users/saveUserRole", qs.stringify(this.roleform))
          .then((response) => {
            this.$refs['tableExt'].refreshTable();
            this.dialogAllowRoleVisible = false;
            this.roledata = [];
            this.roleform.roleIdss = []
            this.roleform.roleIds = ''
          })
          .catch((error) => {
            console.log(error);
            this.roledata = [];
            this.roleform.roleIdss = []
            this.roleform.roleIds =''
          });

      },
      roleQuery: function () {
        debugger;
        //自定义查询待定
        console.log("测试的噢噢噢噢哦哦哦");
      },
      renderFunc(h, option) {
        return <span > {
          option.label
        } </span>;
      },
      resrRoleForm() {
        this.dialogAllowRoleVisible = false;
        this.roledata = [];
        this.roleform.roleIdss = []
      },
      testDate(){
        this.axios.post(this.lib.config.host.system + "/system/rolemgt/roles/getModulesEdit/1/001",).then((response) =>{
          debugger;
        } )
      }
    }
  }
</script>
<style>


</style>
